﻿namespace CookieTerm
{
    using System;
    using System.Runtime.InteropServices;
    using System.Text;
    using System.Windows.Forms;

    public partial class BbsConsole : Control
    {
        const int WM_IME_STARTCOMPOSITION = 0x010D;

        const int CFS_POINT = 0x0002;

        [StructLayout(LayoutKind.Sequential)]
        public struct RECT
        {
            public int Left;
            public int Top;
            public int Right;
            public int Bottom;
        }
        
        [StructLayout(LayoutKind.Sequential)]
        public struct POINT
        {
            public int x;
            public int y;
        }

        [StructLayout(LayoutKind.Sequential)]  
        public struct COMPOSITIONFORM
        {
            public uint dwStyle;
            public POINT ptCurrentPos;
            public RECT rcArea;
        }

        [DllImport("imm32.dll")]
        public static extern IntPtr ImmGetContext(IntPtr hWnd);
        [DllImport("imm32.dll")]
        public static extern bool ImmSetCompositionWindow(IntPtr hIMC, ref COMPOSITIONFORM lpCompForm);
        [DllImport("imm32.dll")]
        public static extern int ImmReleaseContext(IntPtr hWnd, IntPtr hIMC);

        void SetImePosition()
        {
            IntPtr hIMC = ImmGetContext(this.Handle);
            if (hIMC != IntPtr.Zero)
            {
                COMPOSITIONFORM form = new COMPOSITIONFORM();
                form.dwStyle = CFS_POINT;
                form.ptCurrentPos.x = (Controller.CursorColumn - 1) * this.charWidth;
                form.ptCurrentPos.y = (Controller.CursorRow - 1) * this.charHeight;
                ImmSetCompositionWindow(hIMC, ref form);
                ImmReleaseContext(this.Handle, hIMC);
            }   
        }

        protected override void WndProc(ref Message m)
        {
            if (m.Msg == WM_IME_STARTCOMPOSITION)
            {
                SetImePosition();
            }
            base.WndProc(ref m);
        }
    }
}